package servlet;

import cn.hutool.core.util.StrUtil;
import pojo.Product;
import service.ProductService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/index")
public class ProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //操作方法
        String cmd = req.getParameter("cmd");
        //调用方法
        if (StrUtil.isNotBlank("cmd")){
            if(cmd.equals("add")){
                //添加方法
                add(req,resp);
            }
            if (cmd.equals("remove")){
                remove(req,resp);
            }
            if (cmd.equals("clear")){
                clear(req,resp);
            }
        }
    }

    //删除。
    private void clear(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //得到购物车
        HttpSession session = req.getSession();
        ProductService cart = (ProductService) session.getAttribute("cart");
        //清空
        cart.clear();
        resp.sendRedirect("/list.jsp");
    }

    /**
     * 删除
     * @param req
     * @param resp
     */
    private void remove(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //拿到他的pid
        String pid = req.getParameter("pid");
        //得到购物车
        HttpSession session = req.getSession();
        ProductService cart = (ProductService) session.getAttribute("cart");
        //删除操作
        cart.remove(pid);

        resp.sendRedirect("/list.jsp");
    }

    /**
     * 添加
     * @param req
     * @param resp
     * @throws IOException
     */
    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //拿到商品的id
        String pid = req.getParameter("pid");
        //  得到商品的列表
        ServletContext servletContext = req.getServletContext();
        Map<String, Product> products = (Map<String, Product>) servletContext.getAttribute("products");
        //得到购物车对象
        Product product = products.get(pid);
//        得到HttpSession对象
        HttpSession session = req.getSession();
        ProductService cart = (ProductService) session.getAttribute("cart");
        // 如果第一次购物商品，没有购物车就构造一个购物车
        if(cart == null){
            cart = new ProductService();
            //添加商品到购物车中
            cart.add(product);
            // 将购物车放到session中
            session.setAttribute("cart",cart);

            //1.4.6 跳转到购物车列表页面
            resp.sendRedirect("/list.jsp");
        }
    }
}
